package start.spring.basic.flowable.controller.mode;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.security.annotation.RequiresPermissions;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.ApiOperation;
import start.spring.basic.flowable.common.SysConstant;
import start.spring.basic.flowable.controller.BaseController;
import start.spring.basic.flowable.entity.WfCategory;
import start.spring.basic.flowable.service.category.IWfCategoryService;
import start.spring.basic.flowable.service.flowable.IWfModelService;
import start.spring.basic.flowable.vo.flowable.WfModelBo;
import start.spring.basic.flowable.vo.flowable.WfModelExportVo;
import start.spring.basic.flowable.vo.flowable.WfModelVo;
import start.spring.basic.log.ServiceLog;
import start.spring.basic.page.PageQuery;
import start.spring.basic.response.ResponseData;
import start.spring.basic.response.ResponsePage;
import start.spring.basic.util.common.StringUtil;

/**
 * 工作流流程模型管理
 *
 * @author KonBAI
 * @createTime 2022/6/21 9:09
 */
@RestController
@RequestMapping("/model")
public class WfModelController extends BaseController {

	@Autowired
    private IWfModelService modelService;
	
	@Autowired
    private IWfCategoryService categoryService;

    /**
     * 查询流程模型列表
     *
     * @param modelBo 流程模型对象
     * @param pageQuery 分页参数
     */
	@ServiceLog(businessType = "查询流程模型列表", systemType = SysConstant.SYSTEM_TYPE, recordResult = false, userId = "")
	@PostMapping("/list")
	@ApiOperation(value = "查询流程模型列表", notes = "分页查询")
    public ResponsePage<WfModelVo> list(PageQuery pageQuery,@RequestBody WfModelBo modelBo) {
        return super.returnResponse(modelService.list(modelBo, pageQuery));
    }

    /**
     * 查询流程模型历史版本
     *
     * @param modelBo 流程模型对象
     * @param pageQuery 分页参数
     */
	@ServiceLog(businessType = "查询流程模型历史版本", systemType = SysConstant.SYSTEM_TYPE, recordResult = false, userId = "")
	@PostMapping("/historyList")
    @ApiOperation(value = "查询流程模型历史版本", notes = "分页查询")
    public ResponsePage<WfModelVo> historyList(PageQuery pageQuery,@RequestBody WfModelBo modelBo) {
    	String modelKey = modelBo.getModelKey();
    	if(StringUtil.isEmpty(modelKey)) {
    		return ResponsePage.error("请传入模型标识！");
    	}else {
    		return super.returnResponse(modelService.historyList(pageQuery, modelKey));
    	}
    }

    /**
     * 获取流程模型详细信息
     *
     * @param modelId 模型主键
     */
    @GetMapping(value = "/{modelId}")
    public R<WfModelVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable("modelId") String modelId) {
        return R.ok(modelService.getModel(modelId));
    }

    /**
     * 获取流程设计xml
     *
     * @param modelId 模型主键
     */
    @ServiceLog(businessType = "获取流程设计xml", systemType = SysConstant.SYSTEM_TYPE, recordResult = false, userId = "")
    @GetMapping(value = "/bpmnXml/{modelId}")
    @ApiOperation(value = "获取流程设计xml", notes = "")
    public ResponseData<String> getBpmnXml(@NotNull(message = "模型唯一标志不能为空") @PathVariable("modelId") String modelId) {
        return ResponseData.successData(modelService.queryBpmnXmlById(modelId));
    }

    /**
     * 新增流程模型概要信息
     */
    @ServiceLog(businessType = "新增流程模型概要信息", systemType = SysConstant.SYSTEM_TYPE, recordResult = true, userId = "")
    @RequiresPermissions("workflow:model:add")
    @PostMapping("/add")
    @ApiOperation(value = "新增流程模型概要信息", notes = "")
    public ResponseData<Void> add(@Validated @RequestBody WfModelBo modelBo) {
        modelService.insertModel(modelBo);
        return ResponseData.success();
    }

    /**
     * 修改流程模型概要信息
     */
    @ServiceLog(businessType = "修改流程模型概要信息", systemType = SysConstant.SYSTEM_TYPE, recordResult = true, userId = "")
    @RequiresPermissions("workflow:model:edit")
    @PostMapping("/update")
    @ApiOperation(value = "修改流程模型概要信息", notes = "模型概要信息")
    public ResponseData<Void> edit(@Validated @RequestBody WfModelBo modelBo) {
        modelService.updateModel(modelBo);
        return ResponseData.success();
    }

    /**
     * 保存流程模型xml
     */
    @ServiceLog(businessType = "保存流程模型xml", systemType = SysConstant.SYSTEM_TYPE, recordResult = true, userId = "")
    @RequiresPermissions("workflow:model:edit")
    @PostMapping("/save")
    @ApiOperation(value = "保存流程模型xml", notes = "")
    public ResponseData<String> saveModelProcess(@RequestBody WfModelBo modelBo) {
        modelService.saveModelProcess(modelBo);
        return ResponseData.success();
    }

//    /**
//     * 设为最新流程模型
//     * @param modelId
//     * @return
//     */
//    @RequiresPermissions("workflow:model:save")
//    @PostMapping("/latest")
//    public ResponseData<String> latest(@RequestParam String modelId) {
//        modelService.latestModel(modelId);
//        return ResponseData.success();
//    }

    /**
     * 删除流程模型
     *
     * @param modelIds 流程模型主键串
     */
    @ServiceLog(businessType = "删除流程模型", systemType = SysConstant.SYSTEM_TYPE, recordResult = true, userId = "")
    @RequiresPermissions("workflow:model:remove")
    @PostMapping("/remove")
    @ApiOperation(value = "删除流程模型", notes = "按版本删除")
    public ResponseData<String> remove(@RequestBody List<String> modelIds) {
        modelService.deleteByIds(modelIds);
        return ResponseData.success();
    }

    /**
     * 部署流程模型
     *
     * @param modelId 流程模型主键
     */
    @ServiceLog(businessType = "部署流程模型", systemType = SysConstant.SYSTEM_TYPE, recordResult = true, userId = "")
    @RequiresPermissions("workflow:model:edit")
    @GetMapping("/deploy")
    @ApiOperation(value = "部署流程模型", notes = "")
    public ResponseData<Void> deployModel(@RequestParam String modelId) {
    	modelService.deployModel(modelId);
        return ResponseData.successMsg("部署成功！");
    }

    /**
     * 导出流程模型数据
     */
    @RequiresPermissions("workflow:model:export")
    @PostMapping("/export")
    public void export(WfModelBo modelBo, HttpServletResponse response) {
        List<WfModelVo> list =  modelService.list(modelBo);
        List<WfModelExportVo> listVo = BeanUtil.copyToList(list, WfModelExportVo.class);
        List<WfCategory> categoryVos = categoryService.selectWfCategoryList(new WfCategory());
        Map<String, String> categoryMap = categoryVos.stream()
            .collect(Collectors.toMap(WfCategory::getCode, WfCategory::getCategoryName));
        for (WfModelExportVo exportVo : listVo) {
            exportVo.setCategoryName(categoryMap.get(exportVo.getCategory()));
        }
        //TODO 补充导出方法
//        ExcelUtil.exportExcel(listVo, "流程模型数据", WfModelExportVo.class, response);
    }
}
